<template>
    <div class="container added">
        <el-form :model="ruleForm" ref="ruleForm" :rules="rules" :label-position="labelPosition" label-width="120px" class="demo-ruleForm">
            <el-row class="container">
                <el-col :span="12">
                    <el-form-item label="养殖基地：" @click.native="select" prop='plantBaseName'>
                        <el-input placeholder="请输入内容" v-model="ruleForm.plantBaseName"  style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="养殖批号：" @click.native="select">
                        <el-input placeholder="请输入内容" v-model="ruleForm.plantBatch"  style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="基原名称：" @click.native="select">
                        <el-input placeholder="请输入内容" v-model="ruleForm.jyName" style="width:300px"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="养殖地块：" @click.native="select" prop='soilName'>
                        <el-input placeholder="请输入内容" v-model="ruleForm.soilName" style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="养殖时间：" @click.native="select">
                        <el-input placeholder="请输入内容" v-model="ruleForm.plantTime"  style="width:300px"></el-input>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row class="container" STYLE="margin-top:20PX;">
                <el-col :span="12">
                    <el-form-item label="生长天数：">
                        <el-input placeholder='请输入内容' v-model='ruleForm.growYear' style='width: 300px'></el-input>&nbsp;天
                    </el-form-item>
                    <el-form-item label="采收方式：">
                        <el-select v-model="ruleForm.reapWay" placeholder="请选择" style="width:300px;">
                            <el-option label="机械" value="机械"></el-option>
                            <el-option label="人工" value="人工"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="采收批号：" prop='batch'>
                        <el-input placeholder="请输入内容" v-model="ruleForm.batch"  style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="开始时间：">
                        <el-date-picker
                            v-model="ruleForm.beginTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder
                            style="width:300px"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="采收规模：" prop='reapArea'>
                        <el-input placeholder="请输入内容" v-model="ruleForm.reapArea" @change="plants" style="width:300px"></el-input>
                        <span style="margin-left:20px;">张</span>
                    </el-form-item>
                    <el-form-item label="负责人：">
                        <el-select v-model="ruleForm.reapUserName" value-key="id" @change="getuser"  placeholder="" >
                            <el-option v-for="item in userAll" :key="item.id" :label="item.name" :value="item">{{item.name}}</el-option>
                        </el-select>
                        <el-button style="margin-left:10px" @click="gouser">养殖人</el-button>
                    </el-form-item>
                    <el-form-item label="结束时间：" prop='endTime'>
                        <el-date-picker
                            v-model="ruleForm.endTime"
                            type="date"
                            value-format="yyyy-MM-dd"
                            placeholder
                            style="width:300px"
                        ></el-date-picker>
                    </el-form-item>
                </el-col>
            </el-row>


            <el-row class="container" STYLE="margin-top:20PX;" v-for="(item,index) in list" :key ="index">
                <el-col :span="12">
                    <el-form-item label="采收部位：" :prop='"reapPart-"+index'>
                        <el-select v-model="item.reapPart" @change = "getpart(item.reapPart,index)" value-key="id"  placeholder="请选择" style="width:300px;">
                            <el-option v-for="item1 in partlist" :key="item1.id" :label="item1.position" :value="item1">{{item1.position}}</el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="收获数量：" :prop='"reapNumber-"+index'>
                        <el-input placeholder="请输入" v-model="item.reapNumber"  style="width: 200px">
                            <template slot="append">
                                <el-select v-model="item.units"  placeholder="单位"  value-key="id"  style="width:80px !important;background-color: #fff;height: 30px;">
                                    <el-option v-for="item2 in unitList" :key="item2.id" :label="item2.name" :value="item2.name">{{item2.name}}</el-option>
                                </el-select>
                            </template>
                        </el-input>
                        <el-button style="margin-left:10px" @click="gounit">单位管理</el-button>
                    </el-form-item>
                </el-col>
                <el-col :span="10">
                    <el-form-item label="产出物名称：" :prop='"reapName-"+index'>
                        <el-input placeholder="请输入内容" v-model="item.reapName"  style="width:300px"></el-input>
                    </el-form-item>
                    <el-form-item label="操作图片：">
                        <div @click="handelsuccess(index)">
                            <el-upload
                                class="upload-poster"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                :show-file-list="false"
                                :on-change="imgPreview1"
                                :auto-upload="false">
                                <img v-if="item.reapImgs != ''" :src="item.reapImgs" class="avatar">
                                <!-- <img v-else :src="item.reapImg" class="avatar"> -->
                                <i v-else class="el-icon-circle-plus avatar-uploader-icon"></i>
                                <div style="color: #1BC46D;">jpg、png、gif格式，60x60像素，不超过2MB</div>
                            </el-upload>
                        </div>

                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col style='height: 80px'>
                    <el-button @click="add" class='theme-button' style="margin-top:20px;">
                        添加一条
                    </el-button>
                </el-col>
            </el-row>

            <el-form-item class="footerFixed" label-width="0px">
                <div class='fixed'>
                    <el-button class='theme-button' @click="submitrule('ruleForm')">采收提交</el-button>
                    <el-button @click="backPage">返回</el-button>
                </div>
            </el-form-item>
        </el-form>
        <el-dialog title="选择基原" :visible.sync="dialogTableVisible" :modal='false'>
            <el-table
                :data="tableData"
                border
                style="margin-top:20px;"
                ref="multipleTable"
                header-cell-class-name="table-header"
            >
                <el-table-column prop="plantBaseName" sortable label="基地名称"></el-table-column>
                <el-table-column prop="soilName" sortable label="所属地块"></el-table-column>
                <el-table-column prop="jyName" sortable label="基原名称"></el-table-column>
                <el-table-column prop="batch" sortable label="养殖批号"></el-table-column>
                <el-table-column prop="plantTime" sortable label="养殖时间"></el-table-column>
                <el-table-column label="操作" width="150" align="center">
                    <template slot-scope="scope">
                        <el-button
                            type="text"
                            @click="handleSelect(scope.$index, scope.row)"
                        >选择</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <el-pagination layout="total, prev, pager, next, jumper" :page-size="pagesize" :current-page.sync="currentPage" :total="total"  @current-change="handleCurrentChange" style="margin-top:20px"></el-pagination>
        </el-dialog>
    </div>
</template>

<script>
import {
    plant_findByList,
    user_findByAll,
    revovery_part,
    unit_findByList,
    reap_save,
    reap_findById, editRecovery
} from '@/request/api';
import axios from 'axios';
export default {
    props:['recoveryId'],
    data(){
        return{
            formIndex:0,
            hasFile:false,

            list:[{
                reapPart:'',
                reapNumber:'',
                units:'',
                reapName:'',
                reapImg:'',
                reapImgs:''
            }],
            unitList:[],
            partlist:[],
            materialImg:'',
            userAll:'',
            tableData:[],
            total:0,
            currentPage:1,
            pagesize:10,
            dialogTableVisible:false,
            ruleForm:{
                reapArea:''
            },
            batch:'',
            rules:{
                plantBaseName:[
                    { required: true, message: '请输入内容', trigger: 'blur' },
                ],
                batch: [
                    { required: true, message: '请输入内容', trigger: 'blur' },
                ],
                reapArea: [
                    { required: true, message: '请输入内容', trigger: 'blur' },
                ],
                'reapName-0': [
                    { validator:(rule,value,callback)=>{
                            if(this.list[0] && this.list[0].reapName){
                                callback()
                            }else{
                                callback('请填写产出物')
                            }
                        },trigger: 'blur' },
                ],
                reapImg: [
                    { required: true, message: '请上传图片', trigger: 'blur' },
                ],
                'reapPart-0': [
                    { validator:(rule,value,callback)=>{
                            console.log(this.list);
                            if(this.list[0] && this.list[0].reapPart){
                                callback()
                            }else{
                                callback('请选择采收部位')
                            }
                        },trigger: 'blur' },
                ],
                'reapNumber-0': [
                    { validator:(rule,value,callback)=>{
                            if(this.list[0] && this.list[0].reapNumber && this.list[0].units){
                                callback()
                            }else{
                                callback('请输入采收数量并选择单位')
                            }
                        },trigger: 'blur' },
                ],
                endTime: [
                    { required: true, message: '请输入内容', trigger: 'blur' },
                ],
            },
            labelPosition:'right',
            index:"",
            plantArea:'',
            reapTemp:'',
        }
    },
    mounted(){
        console.log('当前编辑id:',this.recoveryId);
        this.init()
        var d = new Date();
        var curr_date = d.getDate();
        var curr_month = d.getMonth() + 1;
        var curr_year = d.getFullYear();
        String(curr_month).length < 2 ? (curr_month = "0" + curr_month): curr_month;
        String(curr_date).length < 2 ? (curr_date = "0" + curr_date): curr_date;
        var yyyyMMdd = curr_year + "" + curr_month +""+ curr_date;
        this.ruleForm.batch = yyyyMMdd + Math.ceil(Math.random()*10000);
        this.batch = this.ruleForm.batch

        this.getFormData()
    },
    watch: {
        //动态表单单独验证每一项
        formIndex(newIndex) {
            // 当formIndex变化时，更新验证规则
            this.rules = this.list.reduce((acc, item, index) => {
                acc[`reapPart-${index}`] = index === newIndex ? { validator:(rule,value,callback)=>{
                        if(this.list[newIndex] && this.list[newIndex].reapPart){
                            callback()
                        }else{
                            callback('请选择采收部位')
                        }
                    }, trigger: 'blur' } : null;
                acc[`reapName-${index}`] = index === newIndex ? { validator:(rule,value,callback)=>{
                        if(this.list[newIndex] && this.list[newIndex].reapName){
                            callback()
                        }else{
                            callback('请输入产出物')
                        }
                    }, trigger: 'blur' } : null;
                acc[`reapNumber-${index}`] = index === newIndex ? { validator:(rule,value,callback)=>{
                        if(this.list[newIndex] && this.list[newIndex].reapNumber && this.list[newIndex].units){
                            callback()
                        }else{
                            callback('请输入产出数量并选择单位')
                        }
                    }, trigger: 'blur' } : null;
                return acc;
            }, {});
        },
    },
    methods:{
        //根据id查询当前数据进行表单回填
        async getFormData(){
            const res = await reap_findById(this.recoveryId)
            if(res.code == 200){
                this.ruleForm = res.data
                this.reapTemp = JSON.stringify(this.ruleForm.reapArea)
                revovery_part(this.ruleForm.jyId).then((res)=>{
                    this.partlist = res.data
                })
            }
        },
        handleClick(params){
            console.log(params);
            this.dialogTableVisibleWorker = true
            this.dialogTitle = params.workBatch
        },
        importExcel(file){
            this.ruleForm.file = file.raw
            this.$notify({
                title: '操作成功',
                message: '导入成功',
                type: 'success'
            })
            this.hasFile = true
        },
        //下载xlsx文件
        downloadFile(url,fileName){
            //由于之前的前端没有封装导入模板接口，所以只能用axios
            axios.get(localStorage.getItem('requestUrl')+url,{responseType:'arraybuffer'}).then(res=>{
                const blob = new Blob([res.data],{type:'application/vnd.ms-excel'})
                const url = window.URL.createObjectURL(blob)
                const link = document.createElement('a')
                link.style.display = 'none'
                link.href = url
                link.setAttribute('download',`${fileName}.xlsx`)
                document.body.appendChild(link)
                link.click()
                document.body.removeChild(link)
                window.URL.revokeObjectURL(url)
                this.$notify({
                    title: '操作成功',
                    message: '下载成功',
                    type: 'success'
                })
            })
        },
        //下载导入模板
        async downloadTemplate() {
            //type (1=农事用工, 2=养殖用工, 3=加工用工, 4=采收用工)
            this.downloadFile('labor/exportLaborTemplate?type=4','采收导入模板')
        },
        plants(){
            if(this.ruleForm.reapArea > this.plantArea){
                this.$notify({
                    title: '提示',
                    message: '采收面积不能大于养殖面积',
                    type: 'info',
                    duration:1000
                });
                this.ruleForm.reapArea = JSON.parse(this.reapTemp)
            }
        },
        gounit(){
            this.$router.push({
                path:'/unit'
            })
        },
        gouser(){
            this.$router.push({
                path:'/staffsManagement/addedstaff'
            })
        },
        handelsuccess(index){
            this.index = index
        },
        add(){
            this.list.push({
                reapPart:'',
                reapNumber:'',
                units:'',
                reapName:'',
                reapImg:'',
                reapImgs:''
            })
        },
        submitrule(){
            this.$refs.ruleForm.validate((valid) => {
                console.log(valid);
                if (valid) {
                    this.$confirm('确定要收获吗？', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        let formdata = new FormData
                        this.ruleForm.reapStatus = 1
                        for(var i=0;i<this.list.length;i++){
                            if(this.list[i].files != "" && this.list[i].files != null){
                                formdata.append("files",this.list[i].files)
                            }
                        }
                        this.ruleForm.reapDetailList = JSON.stringify(this.list)
                        console.log(this.ruleForm)
                        console.log(this.ruleForm.reapDetailList)
                        for(var a in this.ruleForm){
                            if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
                                this.ruleForm[a] = ""
                                formdata.append(a,'')
                            }else{
                                formdata.append(a,this.ruleForm[a])
                            }
                        }
                        editRecovery(formdata).then((res)=>{
                            this.$notify({
                                title: '提示',
                                message: '收获成功',
                                type: 'success',
                                duration:1000
                            });
                            this.$emit('editFinish')
                        })
                    })
                }else{
                    console.log(this.list);
                }
            })

        },
        getpart(ele,index){
            this.formIndex = index
            this.list[index].reapId = ele.id
            this.list[index].reapPart = ele.position
            this.list[index].reapName = ele.name
            // console.log(this.ruleForm)
            console.log(this.list);
        },
        submitrule1(){
            this.$confirm('确定要全部收获吗？此操作后该地块需重新养殖，请谨慎操作', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let formdata = new FormData
                this.ruleForm.reapStatus = 2
                for(var i=0;i<this.list.length;i++){
                    if(this.list[i].files != "" && this.list[i].files != null){
                        formdata.append("files",this.list[i].files)
                    }
                }
                this.ruleForm.reapDetailList = JSON.stringify(this.list)

                for(var a in this.ruleForm){
                    if(this.ruleForm[a] == null || this.ruleForm[a] == "null"){
                        this.ruleForm[a] = ""
                        formdata.append(a,'')
                    }else{
                        formdata.append(a,this.ruleForm[a])
                    }

                }
                reap_save(formdata).then((res)=>{
                    this.$notify({
                        title: '提示',
                        message: '收获成功',
                        type: 'success',
                        duration:1000
                    });
                    this.$router.go(-1)
                })
            })
        },
        backPage(){
            this.$router.go(-1)
        },
        imgPreview1(file,fileList) {
            this.list[this.index].reapImgs =  URL.createObjectURL(file.raw);
            let fileName = file.name;
            let regex = /(.jpg|.gif|.png|.jpeg)$/;
            if (regex.test(fileName.toLowerCase())) {
                this.list[this.index].files = file.raw
                this.list[this.index].reapImg = file.name
            } else {
                this.$message.error('请选择图片文件');
            }
        },
        init(){
            plant_findByList({page:this.currentPage}).then((res)=>{
                this.tableData = res.rows
                this.total = res.total
            })
            user_findByAll("").then((res)=>{
                this.userAll = res.data
            })
            unit_findByList('').then((res) => {
                // if (res.code == 200) {
                this.unitList = res.data;
                // }
            });
        },
        select(){
            this.dialogTableVisible = true
        },
        handleSelect(index,row){
            console.log(row);
            this.dialogTableVisible = false
            this.ruleForm.plantBaseName = row.plantBaseName
            this.ruleForm.soilName = row.soilName
            this.ruleForm.jyName = row.jyName
            this.ruleForm.jyId = row.jyId
            this.ruleForm.plantBatch = row.batch
            this.ruleForm.plantTime = row.plantTime
            this.ruleForm.reapArea = row.plantArea
            this.plantArea = row.plantArea
            revovery_part(row.jyId).then((res)=>{
                this.partlist = res.data
            })
        },
        getuser(ele){
            this.ruleForm.reapUserId = ele.id
            this.ruleForm.reapUserName = ele.name
        },
        handleCurrentChange(val){
            this.currentPage = val
            this.init()
        },
    }
}
</script>

<style lang='less' scoped>
@import "@/assets/css/common.less";
.el-pagination{
    text-align: right;
}
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    width:180px;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}
.el-upload--text{
    width:180px;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 90px;
    /* height: 178px; */
    line-height: 140px;
    text-align: center;
    color: #1BC46D;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
<style lang="less">
.added {
    .el-input .el-input__inner {
        background-color: #FAFAFA !important;
        border: 1px solid #EEEEEE !important;
    }

    .el-textarea__inner {
        background-color: #FAFAFA !important;
        border: 1px solid #EEEEEE !important;
    }
}
</style>
